<template>
  <view
    style="height: 44px"
    class="flex justify-center items-center position-relative"
    @touchstart="touchstart"
    @touchmove="touchmove"
    @touchend="touchend"
    @touchcancel="touchcancel"
  >
    <!-- flex-1 -->
    <view
      class="process-bar-wrap rounded position-relative shrink-0"
      style="height: 3px; background-color: rgb(255 255 255 / 50%)"
      :style="{ width: `${progressWidth + dotWidth}px` }"
    >
      <view class="process-bar bg-fuchsia" style="height: 100%" :style="activeStyle"></view>
      <view class="progress-bar-dot position-absolute bg-fuchsia-4" :style="activeDotStyle"></view>
    </view>
  </view>
</template>

<script setup>
import { onMounted } from 'vue'

const props = defineProps({
  currentTime: {
    type: Number,
    default: 0,
  },
  duration: {
    type: Number,
    default: 0,
  },
  progressWidth: {
    type: [String, Number],
    default: 0,
  },
  progressLeft: {
    type: [String, Number],
    default: 0,
  },
  dotWidth: {
    type: [String, Number],
    default: 0,
  },
  isDisabled: {
    type: Boolean,
    default: false,
  },
})

const emits = defineEmits(['change', 'update'])

const activeWidth = ref(0) // 进度条宽度
const moveStatus = ref(false) // 是否拖拽

const activeStyle = computed(() => {
  return {
    width: `${activeWidth.value}px`,
  }
})

const activeDotStyle = computed(() => {
  return {
    // 到右边边界需要处理
    left: `${activeWidth.value}px`,
    width: `${props.dotWidth}px`,
    height: `${props.dotWidth}px`,
  }
})

// 当前时长
const current = computed(() => {
  return props.progressWidth === 0 ? 0 : (activeWidth.value / props.progressWidth) * props.duration
})

watch(
  () => props.currentTime,
  () => {
    if (!moveStatus.value) {
      active()
    }
  },
)

const active = () => {
  activeWidth.value =
    props.duration === 0 ? 0 : (props.currentTime / props.duration) * props.progressWidth
}

const touchstart = (e) => {
  if (props.isDisabled) return

  if (props.duration === 0) return
  moveStatus.value = true
  activeWidth.value = e.changedTouches[0].screenX - props.progressLeft
}

const touchmove = (e) => {
  if (props.isDisabled) return
  if (props.duration === 0) return
  const d = e.changedTouches[0].screenX - props.progressLeft

  if (d <= 0) {
    activeWidth.value = 0
  } else if (d >= props.progressWidth) {
    activeWidth.value = props.progressWidth
  } else {
    activeWidth.value = d
  }

  emits('update', current.value)
}

const touchend = (e) => {
  if (props.isDisabled) return
  if (props.duration === 0) return
  moveStatus.value = false
  emits('change', current.value)
}

const touchcancel = (e) => {
  touchend(e)
}

onMounted(() => {
  active()
})
</script>

<style lang="scss" scoped>
.progress-bar-dot {
  top: 50%;
  border-radius: 100%;
  transform: translateY(-50%);
}
</style>
